﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.Linq.SqlClient;

public partial class User_ContractInformation : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected int getMonthCountPayment()
    {
        var payments = from payment in db.ContractPayments where payment.ConractId == getContractId() select payment;
        Contract contract = getContract(getContractId());
        DateTime maxDate = contract.CreationDate;
        foreach (ContractPayment contractPayment in payments)
        {
            if (contractPayment.Date > maxDate)
            {
                maxDate = contractPayment.Date;
            }
        }
        return SqlMethods.DateDiffMonth(contract.CreationDate, maxDate);
    }

    protected Contract getContract(int contractId)
    {
        var contracts = from contract in db.Contracts where contract.ContractId == contractId select contract;
        if (contracts.Count() > 0)
        {
            return contracts.First();
        }
        return null;
    }

    protected int getContractId()
    {
        string contractId = null;
        if (Session["contractId"] != null)
        {
            contractId = Session["contractId"].ToString();
            return Convert.ToInt32(contractId);
        }
        return -1;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("User"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        Contract selectedContract = getContract(getContractId());
        if (!selectedContract.Credit.AdvancedRepayment)
        {
            int paymentCounts = getMonthCountPayment();
            int maxPaymentCountsForToday = SqlMethods.DateDiffMonth(selectedContract.CreationDate, DateTime.Now);
            if (paymentCounts >= maxPaymentCountsForToday)
            {
                PaymentButton.Enabled = false;
            }
        }
        if (selectedContract.StatusId == 1)
        {
            PaymentButton.Visible = true;
        }
        else
        {
            PaymentButton.Visible = false;
        }
    }
    protected void PaymentButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/User/Payment.aspx");
    }
}